package xyz.kongbai121.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import xyz.kongbai121.demo.domain.Article;
import xyz.kongbai121.demo.domain.RespBean;
import xyz.kongbai121.demo.service.IArticleService;
import xyz.kongbai121.demo.util.SensitiveWord;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 文章处理控制器
 * @author 空白
 */
@RestController
@RequestMapping("/Article")
public class ArticleController {

    @Autowired
    private IArticleService service;

    @RequestMapping("/save")
    public RespBean saveArticle(String head, String body, String imgPath, String token){
        //敏感字符处理
        String securityHead = SensitiveWord.getSensitiveWord().filterInfo(head);
        String securityBody = SensitiveWord.getSensitiveWord().filterInfo(body);
        //保存业务
        String msg = service.save(securityHead, securityBody, imgPath, token);
        return new RespBean(true,msg);
    }

    @RequestMapping("/img")
    public Map<String,String> img(@RequestPart MultipartFile file){
        Map<String, String> map = new HashMap<>();
        //如果有文件
        if (file.getSize()>0){
            String fileName = file.getOriginalFilename();
            String serverFileName = "../userdata/"+fileName;
            File co = new File(serverFileName);
            try {
                Files.copy(file.getInputStream(),co.toPath());
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println(fileName);
            map.put("serverFileName",fileName);
        }
        return map;
    }

    @RequestMapping("/list")
    public List<Article> listArticle(String title){
        try {
            if (title!=null&&!title.isEmpty()) {
                //清除前后空格,中间的空格用百分号代替
                String head = title.trim().replaceAll(" ", "%");
                return service.list("%" + head + "%");
            }
            return service.list(null);
        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<>();
        }
    }

    @RequestMapping("/get")
    public Article getArticle(Long id){
        try {
            return service.get(id);
        } catch (Exception e) {
            e.printStackTrace();
            return new Article();
        }
    }

    @RequestMapping("/delete")
    public RespBean deleteArticle(Long id, String token){
        String msg = service.delete(id, token);
        return new RespBean(true,msg);
    }

}
